import pymysql


# 定义数据库工具类
class DBTools(object):
    # 创建连接
    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123456",
                               database="study", charset="utf8")
        return conn

    # 查一条记录
    @classmethod
    def query_one(cls, sql):
        my_conn = None
        my_cursor = None
        res = None
        try:
            # 创建连接
            my_conn = DBTools.__create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行 sql 语句
            my_cursor.execute(sql)
            # 提取一条记录
            res = my_cursor.fetchone()
        except Exception as err:
            print("执行查询SQL失败：", str(err))
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
            # 返回查询结果
            return res

    # 查所有记录
    @classmethod
    def query_all(cls, sql):
        my_conn = None
        my_cursor = None
        res = None
        try:
            # 创建连接
            my_conn = DBTools.__create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行 sql 语句
            my_cursor.execute(sql)
            # 提取一条记录
            res = my_cursor.fetchall()
        except Exception as err:
            print("执行查询SQL失败：", str(err))
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()
            # 返回查询结果
            return res


    # 增删改记录
    @classmethod
    def db_uid(cls, sql):
        my_conn = None
        my_cursor = None
        try:
            # 创建连接
            my_conn = DBTools.__create_conn()
            # 创建游标
            my_cursor = my_conn.cursor()
            # 执行增删改语句
            my_cursor.execute(sql)
            print("Affected rows:", my_conn.affected_rows())
            # 提交事务
            my_conn.commit()
        except Exception as err:
            print("执行 增删改 SQL 失败：", str(err))
            # 回滚事务
            my_conn.rollback()
        finally:
            # 关闭游标
            my_cursor.close()
            # 关闭连接
            my_conn.close()


if __name__ == '__main__':
    DBTools.db_uid("INSERT INTO user_profile VALUES(6,3214,'male',null,'111','111');")
    result = DBTools.query_all("select * from user_profile where gender is null;")
    print("查询语句的结果：", result)
    DBTools.db_uid("delete from user_profile where university = '浙江大学';")



